package app.Disthanitian.thaistyle.EmerMez;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends Activity {

	static UrlEmerMez URLlink = new UrlEmerMez();

	public static final String url = URLlink.getUrllogin();
	public static final String urlGETID = URLlink.getUrlgetid();
	public static String result = "";
	Intent newAct;
	public static String email;
	public static String password;
	JSONArray jArray;
	InputStream is = null;
	String js_result = "";
	HttpPost httppost = null;
	JSONObject jo=null;
	MemberUser user = new MemberUser();
	
	SessionManager session;
	String id2;
	String name2;
	String email2;
	String msgYel2 ;
	String msgRed2;
	int time2;

	protected void onCreate(Bundle saveInstanceState) {
		super.onCreate(saveInstanceState);
		setContentView(R.layout.login);
		
		// Session Manager
        session = new SessionManager(getApplicationContext()); 
        
        Toast.makeText(getApplicationContext(), "User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG).show();
		
        session.checkLogin();
        
        //CheckFirstLogin();
		Button bt_login = (Button) findViewById(R.id.login);
		TextView bt_signup = (TextView) findViewById(R.id.signup1);
		Button bt_gomap = (Button) findViewById(R.id.goMap);
		Button bt_goStatus = (Button) findViewById(R.id.goStatus);
		Button bt_goSetting = (Button) findViewById(R.id.GoSetting);
		TextView bt_forgetpass = (TextView) findViewById(R.id.forgetpassword);

		bt_goSetting.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				newAct = new Intent(LoginActivity.this, SettingActivity.class);
				startActivity(newAct);

			}
		});

		bt_goStatus.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				newAct = new Intent(LoginActivity.this, ChangeStatus.class);
				startActivity(newAct);

			}
		});

		bt_gomap.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				newAct = new Intent(LoginActivity.this, MainActivity.class);
				startActivity(newAct);

			}
		});
		bt_login.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				WebPageTask task = new WebPageTask();
				task.execute();

				RunBg a = new RunBg();
				a.execute();

			}
		});

		bt_signup.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				newAct = new Intent(LoginActivity.this, RegisterActivity.class);
				startActivity(newAct);
			}
		});

		bt_forgetpass.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				newAct = new Intent(LoginActivity.this, ForgetPassword.class);
				startActivity(newAct);

			}
		});

	}

	private void CheckFirstLogin() {
		String Status = user.getStatusLogin();
		Toast.makeText(LoginActivity.this, Status,Toast.LENGTH_LONG).show();
		//------------------
		
		String value;
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
		    value = extras.getString("StatusLogout");
		    Status = value;
		}
		//----------------
		if(Status=="login"){
			newAct = new Intent(LoginActivity.this, ChangeStatus.class);
			startActivity(newAct);
			
		}
		
	}

	public String login() {
		EditText edittext_email = (EditText) findViewById(R.id.edittext_email);
		EditText edittext_password = (EditText) findViewById(R.id.edittext_password);

		email = edittext_email.getText().toString();
		password = edittext_password.getText().toString();
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
		nameValuePairs.add(new BasicNameValuePair("email", email));
		nameValuePairs.add(new BasicNameValuePair("password", password));
		return postData(url, nameValuePairs);
	}

	public String ShowID() {

		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
		nameValuePairs.add(new BasicNameValuePair("email", email));

		return postDataID(urlGETID, nameValuePairs);
	}

	private String postDataID(String url, List<NameValuePair> nameValuePairs) {
		HttpClient httpclient = new DefaultHttpClient();
		httppost = new HttpPost(url);
		BufferedReader in = null;
		StringBuffer sb = new StringBuffer("");

		try {
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			in = new BufferedReader(new InputStreamReader(response.getEntity()
					.getContent()));

			// StringBuilder sb = new StringBuilder();

			String line;
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			js_result = sb.toString();
			return js_result;
		} catch (ClientProtocolException e) {
			Log.e("log_tag", "Error converting result " + e.toString());
		} catch (IOException e) {
		}
		return null;
	}

	public String postData(String url, List<NameValuePair> nameValuePairs) {
		HttpClient httpclient = new DefaultHttpClient();
		httppost = new HttpPost(url);
		BufferedReader in = null;

		try {
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			in = new BufferedReader(new InputStreamReader(response.getEntity()
					.getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			String page = sb.toString();
			return page;
		} catch (ClientProtocolException e) {

		} catch (IOException e) {

		}
		return null;

	}

	protected class WebPageTask extends AsyncTask<Void, Void, String> {

		@Override
		protected String doInBackground(Void... params) {
			result = login();
			return result;
		}
		protected void onPostExecute(String result) {
			if (result.trim().equals("ok")) {
				
				
				
				Toast.makeText(LoginActivity.this, "Login success ",Toast.LENGTH_LONG).show();
				
			
				
				newAct = new Intent(LoginActivity.this, ChangeStatus.class);
				// newAct.putExtra("MemberEmail", email);
				// Send data with Intent
				user.setEmail(email); // set email
				Toast.makeText(LoginActivity.this, "Welcome " + email,Toast.LENGTH_LONG).show();
				startActivity(newAct);
				
				

			} else {
				Toast.makeText(LoginActivity.this,"Incorrect username and password ", Toast.LENGTH_LONG).show();
			}
		}

	}

	protected class RunBg extends AsyncTask<Void, Void, String> {

		@Override
		protected String doInBackground(Void... params) {

			result = ShowID();
			return result;
		}

		protected void onPostExecute(String result) {
			//Toast.makeText(LoginActivity.this, result,Toast.LENGTH_LONG).show();

			try {

				JSONArray jArray = new JSONArray(result);
			
				for (int i = 0; i < jArray.length(); i++) {
					jo = jArray.getJSONObject(i);
				
					
					String id = jo.getString("user_id");
					String email = jo.getString("email");
					String firstname = jo.getString("firstname");
					String password = jo.getString("password");
					String lastname = jo.getString("lastname");
					String phoneNum = jo.getString("phonenum");
					int timeLocateUpdate = jo.getInt("timeupdate");
					String pinCode = jo.getString("pincode");
					String msgRed = jo.getString("msgred");
					String msgYellow =  jo.getString("msgyellow");
					String confirmation = jo.getString("comfirmation");
					String type = jo.getString("type"); 
				   
					

					MemberUser.setId(id);
					MemberUser.setEmail(email);
					MemberUser.setFirstname(firstname);
					MemberUser.setLastname(lastname);
					MemberUser.setPassword(password);
					MemberUser.setPhoneNum(phoneNum);
					MemberUser.setPinCode(pinCode);
					MemberUser.setTimeLocateUpdate(timeLocateUpdate);
					MemberUser.setType(type);
					MemberUser.setMsgRed(msgRed);
					MemberUser.setMsgYellow(msgYellow);
					MemberUser.setConfirmation(confirmation);
				
					

					id2 = MemberUser.getId();
					name2 = MemberUser.getFirstname();
					email2= MemberUser.getEmail();
					time2 = MemberUser.getTimeLocateUpdate();
					msgYel2 = MemberUser.getMsgYellow();
					msgRed2 = MemberUser.getMsgRed();
					
					session.createLoginSession(name2,email2,id2,String.valueOf(time2),msgYel2,msgRed2);
					
					
					//Toast.makeText(LoginActivity.this, session.createLoginSession(id2) , Toast.LENGTH_LONG).show();
					
					Toast.makeText(LoginActivity.this, "ID :"+ id2+"  time"+time2 , Toast.LENGTH_LONG).show();
				   //	Toast.makeText(LoginActivity.this, jo.getString("phonenum")+"||"+jo.getString("timeupdate")+"||"+jo.getString("pincode")+"||"+jo.getString("msgred")+"||"+jo.getString("msgyellow")+""+jo.getString("type")+"||"+jo.getString("type"), Toast.LENGTH_LONG).show();
					//Toast.makeText(LoginActivity.this, jo.getString("confirmation"), Toast.LENGTH_LONG).show();

				}
			} catch (JSONException e) {
				Log.e("log_tag", "Error parsing data " + e.toString());

			}

		}
	}

}
